package com.yueke.camp.campweb.campweb.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yueke.camp.campmodel.campdto.activity.AddCampActivityOrdersParam;
import com.yueke.camp.campmodel.campdto.activity.FindActivityOrdersParam;
import com.yueke.camp.campmodel.campdto.rv.FindRvOrdersConditionParam;
import com.yueke.camp.campmodel.campdto.rv.PayRvOrdersParam;
import com.yueke.camp.campweb.campweb.config.AlipayConfig;
import com.yueke.camp.campweb.campweb.service.YuekeActivityOrdersService;
import com.yueke.common.core.domain.camp.YuekeActivityOrders;
import com.yueke.common.core.domain.camp.YuekeRvOrders;
import com.yueke.common.core.dto.ResultDto;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiyang
 * @since 2020-10-14
 */
@RestController
@RequestMapping("/camp")
public class YuekeActivityOrdersController {
    @Autowired
    private YuekeActivityOrdersService yuekeActivityOrdersService;

    @PostMapping("/activity/addActivityOrders")
    @ApiOperation("新增活动订单")
    public ResultDto addActivityOrders(@RequestBody AddCampActivityOrdersParam addCampActivityOrdersParam){
        System.out.println(addCampActivityOrdersParam.toString());
        yuekeActivityOrdersService.addActivityOrders(addCampActivityOrdersParam);
        return ResultDto.success().setMsg("下单成功").setCode(200);
    }

    /**
     * 条件查询订单列表
     * @param findActivityOrdersParam
     * @return
     */
    @GetMapping("/activity/selectActivityOrdersByCondition")
    @ApiOperation(value = "条件查询活动订单列表")
    public ResultDto findRVOrdersByCondition(FindActivityOrdersParam findActivityOrdersParam){
        QueryWrapper<YuekeActivityOrders> queryWrapper = new QueryWrapper<>();
        if(findActivityOrdersParam.getYuejeActivityCampId()!=null){
            queryWrapper.eq("yueje_activity_camp_id",findActivityOrdersParam.getYuejeActivityCampId());
        }
        if(findActivityOrdersParam.getYuekeActivityId()!=null){
            queryWrapper.eq("yueke_activity_id",findActivityOrdersParam.getYuekeActivityId());
        }
        if(findActivityOrdersParam.getYuekeActivityOrdersId()!=null){
            queryWrapper.eq("yueke_activity_orders_id",findActivityOrdersParam.getYuekeActivityOrdersId());
        }
        if(findActivityOrdersParam.getYuekeActivityOrdersPaystatus()!=null){
            queryWrapper.eq("yueke_activity_orders_paystatus",findActivityOrdersParam.getYuekeActivityOrdersPaystatus());
        }
        if(findActivityOrdersParam.getYuekeActivityUserId()!=null){
            queryWrapper.eq("yueke_activity_user_id",findActivityOrdersParam.getYuekeActivityUserId());
        }
        Page<YuekeActivityOrders> yuekeActivityOrdersPage = new Page<>(findActivityOrdersParam.getPageNumber(), findActivityOrdersParam.getPageSize());
        Page<YuekeActivityOrders> page = yuekeActivityOrdersService.page(yuekeActivityOrdersPage, queryWrapper);
        if(page.getRecords().isEmpty()){
            return ResultDto.success().setCode(500).setMsg("查询为空");
        }
        return ResultDto.success().setCode(200).setMsg("查询成功").setData(page);
    }


    @PostMapping("/activity/payPayOrders")
    @ApiOperation(value = "活动订单支付")
    public String  payController (@RequestBody PayRvOrdersParam payRvOrdersParam) throws IOException {
        System.out.println("11111111111111111111111");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        Integer ordersId = payRvOrdersParam.getOrdersId();
        // String out_trade_no = request.getParameter("Order");
        //付款金额，必填  ShopName
        BigDecimal totalprice = payRvOrdersParam.getTotalprice();
        //String total_amount = request.getParameter("Money");
        //订单名称，必填
        String name = payRvOrdersParam.getName();
        //String subject = request.getParameter("Name");
        //商品描述，可空
        String body = "房车订单测试";
        System.out.println(ordersId+":"+totalprice+":"+name+":"+body);
        // String body =request.getParameter("购物测试");
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + ordersId + "\","
                + "\"total_amount\":\"" + totalprice + "\","
                + "\"subject\":\"" + name + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String url = "";
        try {
            url = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            System.out.println(url);
               /* response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);

                response.getWriter().write(url); // 直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();*/

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        return url;
    }



}

